(function () {

    var P = require('./config.js').pathes,
        fs = require('fs'),
        path = require('path')

    var sassFiles = [
        {
            floder: P.src + '/modules',
            target: P.src + '/common/common.scss'
        }
    ]
    function getSassPathes(sassBasePath) {
        var sassTarget = sassBasePath.target
        sassBasePath = sassBasePath.floder

        var sassPathes = fs
            .readdirSync(sassBasePath)
            .filter(function (floder) {
                return floder !== 'common'
            })
            .map(function (floder) {
                var curPath = path.join(sassBasePath, floder),
                    isDirectory = fs.statSync(curPath).isDirectory()

                if (isDirectory) {
                    var sassFile = fs.readdirSync(curPath)
                        .filter(function (file) {
                            return path.extname(file) == '.scss'
                        })
                }

                if (sassFile && sassFile[0]) {
                    return path.join(curPath, sassFile[0])
                }
            })
            .filter(function (path) {
                return path
            })

        return sassPathes
            .map(function (pathItem) {
                var relativePath = path.relative(sassTarget, pathItem).replace(/\\/g, '/').replace(/\.\.\//, '')
                return '\n@import "' + relativePath + '";'
            })
    }

    function importSass(pathes, destination) {
        var importFlag = '\n\/\/new import',

            oldData = fs.readFileSync(destination, 'utf8'),
            newImport = pathes.join('')

        if (oldData.indexOf(importFlag) > -1) {
            var oldDataArr = oldData.split(importFlag)
            if (oldDataArr[1] == newImport) return
            if(!oldDataArr || !oldDataArr[0]) return
            oldData = oldDataArr[0]
        }

        var newData = oldData + importFlag + newImport
        fs.writeFileSync(destination, newData)
    }

    function mergeSass() {
        sassFiles.forEach(function (item) {
            importSass(getSassPathes(item), item.target)
        })
    }

    module.exports = mergeSass

}())